#include <cmath>
#include <string>
#include <GL/glew.h>

#include <SRL/Utils/Vector.h>
#include <SRL/Utils/Color.h>
#include <SRL/Utils/BoundingBox.h>

namespace srl {
    
    static float Vertices[] = {
       -1.0f,-1.0f, 1.0f,
        1.0f,-1.0f, 1.0f,
        1.0f, 1.0f, 1.0f,
       -1.0f, 1.0f, 1.0f,
      
       -1.0f,-1.0f,-1.0f,
       -1.0f, 1.0f,-1.0f,
        1.0f, 1.0f,-1.0f,
        1.0f,-1.0f,-1.0f,
      
       -1.0f, 1.0f,-1.0f,
       -1.0f, 1.0f, 1.0f,
        1.0f, 1.0f, 1.0f,
        1.0f, 1.0f,-1.0f,
     
       -1.0f,-1.0f,-1.0f,
        1.0f,-1.0f,-1.0f,
        1.0f,-1.0f, 1.0f,
       -1.0f,-1.0f, 1.0f,
      
        1.0f,-1.0f,-1.0f,
        1.0f, 1.0f,-1.0f,
        1.0f, 1.0f, 1.0f,
        1.0f,-1.0f, 1.0f,
  
       -1.0f,-1.0f,-1.0f,
       -1.0f,-1.0f, 1.0f,
       -1.0f, 1.0f, 1.0f,
       -1.0f, 1.0f,-1.0f
    };

    
    BoundingBox::BoundingBox() { }
    BoundingBox::BoundingBox(srl::BoundingBox *box) { Min = box->Min; Max = box->Max; }
    BoundingBox::BoundingBox(srl::Vector<float> min, srl::Vector<float> max) { Min = min; Max = max; }
    BoundingBox::~BoundingBox() { }
    
    BoundingBox BoundingBox::operator=(srl::BoundingBox box) {
        Min = box.Min;
        Max = box.Max;
    }
    
    srl::Vector<float> BoundingBox::GetCenter() {
        return GetSize()/2;
    }
    srl::Vector<float> BoundingBox::GetSize() {
        return Max-Min;
    }
    
    void BoundingBox::Set(srl::Vector<float> min, srl::Vector<float> max) { Min = min; Max = max; }
    
    bool BoundingBox::IsIn(srl::Vector<float> point, bool z) {
        if( point.x > Min.x && point.x < Max.x   &&  point.y > Min.y && point.y < Max.y) {
            if(!z)
                return true;
            else if( point.z > Min.z && point.z < Max.z)
                return true;
            else
                return false;
        }
        else
            return false;
    }
    
    void BoundingBox::Draw(srl::Color color) {
        srl::Vector<float> Center = GetCenter();
        srl::Vector<float> Size = GetSize();
        
        glEnable( GL_POLYGON_OFFSET_LINE );
        glPolygonOffset( -1.0f, -2.0f );
        
        glColor4f(color.r, color.g, color.b, color.a);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        
        glDisable(GL_TEXTURE_2D);
        
        glPushMatrix();
           glTranslatef(Center.x, Center.y, Center.z);
           glScalef(Size.x, Size.y, Size.z);
        
         glInterleavedArrays( GL_V3F, 0, Vertices );
         glDrawArrays( GL_QUADS, 0, 24 );
        glPopMatrix();
        
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glDisable( GL_POLYGON_OFFSET_LINE );
        glColor4f(1,1,1,1);
    }       
};
